package com.platform.activiti.web;

import com.platform.activiti.dto.DeploymentBean;
import com.platform.activiti.dto.TaskBean;
import com.platform.activiti.dto.WorkFlow;
import com.platform.activiti.service.EasyActService;
import com.platform.activiti.dto.ProcessDefinitionBean;
import com.platform.utils.UploadUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Comment;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工作流微服务
 *
 * @author 王玉涛
 * @Param
 * @date 2017-09-28 13:48
 */
@RestController
@RequestMapping("easyAct")
public class EasyActConctroller {

    @Autowired
    private EasyActService easyActService;
//    @Autowired
//    private HttpServletResponse response;

    @ApiOperation(value = "部署管理首页显示", notes = "")
    @PostMapping("deployHome")
    public List<DeploymentBean> deployHome() {
        List<DeploymentBean> depList = easyActService.findDeploymentList();
        return depList;
    }

    @ApiOperation(value = "流程定义首页显示", notes = "")
    @PostMapping("processHome")
    @ApiImplicitParams({@ApiImplicitParam(name = "page", paramType = "query", value = "页码", dataType = "Integer")
            , @ApiImplicitParam(name = "pageSize", paramType = "query", value = "页容", dataType = "Integer")
    })
    public List<ProcessDefinitionBean> processHome(Integer page, Integer pageSize) {
        List<ProcessDefinitionBean> pdList = easyActService.findProcessDefinitionList(page, pageSize);
        return pdList;
    }
//    @ApiOperation(value = "部署管理首页显示", notes = "")
//    @GetMapping("deployHome")
//    public Map<String, Object> deployHome(Integer page, Integer pageSize) {
//        Map<String, Object> map = new HashMap<>();
//        // 1:查询部署对象信息，对应表（act_re_deployment）
//        try {
//            List<DeploymentBean> depList = easyActService.findDeploymentList(page,pageSize);
//            map.put("depList", depList);
//        } catch (Exception e) {
//            map.put("depList", null);
//        }
//        try {
//            // 2:查询流程定义的信息，对应表（act_re_procdef）
//            List<ProcessDefinitionBean> pdList = easyActService.findProcessDefinitionList(page,pageSize);
//            // 放置到map对象中
//            map.put("pdList", pdList);
//        } catch (Exception e) {
//            // 放置到map对象中
//            map.put("pdList", null);
//        }
//        return map;
//    }

    @ApiOperation(value = "发布流程", notes = "")
    @PostMapping("newdeploy")
    @ApiImplicitParam(name = "filename", paramType = "query", value = "业务实体类名称", dataType = "String")
    public String newdeploy(MultipartFile file, @RequestParam("filename") String filename) {

        // 获取页面传递的值
        // 1：获取页面上传递的zip格式的文件，格式是MultipartFile类型
        // 2：调用上传文件方法，存储file
        // 方法返回值为路径+文件名
        try {
            String path = easyActService.fileUpload(file);
            // 指向文件路径
            File f = new File(path);
            // 完成部署
            easyActService.saveNewDeploye(f, filename);
            return "新增成功";
        } catch (Exception e) {
            return "新增流程未成功，请检查上传参数是否正确";
        }

    }

    @ApiOperation(value = "删除部署信息", notes = "")
    @PostMapping(value = "delDeployment")
    @ApiImplicitParam(name = "deploymentId", paramType = "query", value = "部署对象ID", dataType = "String")
    public String delDeployment(String deploymentId) {
        // 1：获取部署对象ID
        // 部署对象ID
        // 2：使用部署对象ID，删除流程定义
        try {
            easyActService.deleteProcessDefinitionByDeploymentId(deploymentId);
        } catch (Exception e) {

            return "删除失败，请确认该部署流程是否存在";
        }
        return "删除成功";
    }

    @ApiOperation(value = "查看流程图", notes = "")
    @PostMapping(value = "viewImage")
    @ApiImplicitParam(name = "taskId", paramType = "query", value = "任务ID", required = true, dataType = "String")
    public String viewImage(String taskId) throws Exception {

        // 1：获取页面传递的部署对象ID和资源图片名称
        // 部署对象ID
        ProcessDefinition pd = easyActService.getProcessDefinitionByTaskId(taskId);
        // 1. 获取流程部署ID
        String deploymentId = pd.getDeploymentId();
//        String deploymentId = workFlow.getDeploymentId();
        // 资源图片名称
        String imageName = pd.getDiagramResourceName();
//        String imageName = workFlow.getImageName();
        // 2：获取资源文件表（act_ge_bytearray）中资源图片输入流InputStream
        InputStream in = easyActService.findImageInputStream(deploymentId, imageName);
        // 将图片转换成字符串
        byte[] bytes = new byte[in.available()];
        in.read(bytes);
        String imgStr = UploadUtil.byte2hex(bytes);
//        // 3：从response对象获取输出流
//        OutputStream out = response.getOutputStream();
//        // 4：将输入流中的数据读取出来，写到输出流中
//        for (int b = -1; (b = in.read()) != -1; ) {
//            out.write(b);
//        }
//
//        // 将图写到页面上，用输出流写
//        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//        StringBuilder sb = new StringBuilder();
//        String line;
//        while ((line = reader.readLine()) != null) {
//            sb.append(line + "/r/n");
//        }
//        out.close();
        in.close();

        return imgStr;
    }

    @ApiOperation(value = "查看流程图By流程定义ID", notes = "")
    @PostMapping(value = "viewImageByProId")
    @ApiImplicitParam(name = "proId", paramType = "query", value = "流程定义ID", required = true, dataType = "String")
    public String viewImageByProId(String proId) throws Exception {

        // 1：获取页面传递的部署对象ID和资源图片名称
        // 部署对象ID
        ProcessDefinition pd = easyActService.getProcessDefinitionById(proId);
        // 资源图片名称
        // 1. 获取流程部署ID
        String deploymentId = pd.getDeploymentId();
        String imageName = pd.getDiagramResourceName();
//        String imageName = workFlow.getImageName();
        // 2：获取资源文件表（act_ge_bytearray）中资源图片输入流InputStream
        InputStream in = easyActService.findImageInputStream(deploymentId, imageName);
        // 将图片转换成字符串
        byte[] bytes = new byte[in.available()];
        in.read(bytes);
        String imgStr = UploadUtil.byte2hex(bytes);
        in.close();
        return imgStr;
    }

    @ApiOperation(value = "查看流程图By流程部署ID", notes = "")
    @PostMapping(value = "viewImageByDepId")
    @ApiImplicitParam(name = "depId", paramType = "query", value = "流程部署ID", required = true, dataType = "String")
    public String viewImageByDepId(String depId) throws Exception {
        // 获取资源文件表（act_ge_bytearray）中资源图片输入流InputStream
        // 获取流程定义by部署对象ID
        ProcessDefinition pd = easyActService.getProcessDefinitionByDepId(depId);
        String imageName = pd.getDiagramResourceName();
        InputStream in = easyActService.findImageInputStream(depId, imageName);
        // 将图片转换成字符串
        byte[] bytes = new byte[in.available()];
        in.read(bytes);
        String imgStr = UploadUtil.byte2hex(bytes);
        in.close();
        return imgStr;
    }

    @ApiOperation(value = "删除流程实例by任务id", notes = "")
    @PostMapping(value = "deleteProcessInstance")
    @ApiImplicitParam(name = "taskId", paramType = "query", value = "任务ID", required = true, dataType = "String")
    public String deleteProcessInstance(String taskId) throws Exception {
        return easyActService.deleteProcessInstance(taskId);
    }

    @ApiOperation(value = "启动流程实例", notes = "使用流程定义的key，启动流程实例，同时设置流程变量，同时向正在执行的执行对象表中的字段BUSINESS_KEY添加业务数据，同时让流程关联业务")
    @PostMapping("startProcess")
    @ApiImplicitParams({@ApiImplicitParam(name = "className", value = "业务类名", required = true, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "objId", value = "业务id", dataType = "String", required = true, paramType = "query")
            , @ApiImplicitParam(name = "assignee", value = "办理人", dataType = "String", required = true, paramType = "query")
    })
    public String saveStartProcess(String className, String objId, String assignee) {
        try {
            Map<String, Object> variables = new HashMap();
            variables.put("assignee", assignee);
            easyActService.saveStartProcess(className, objId, variables);
            return "启动流程成功";
        } catch (Exception e) {
            return "启动流程失败";
        }
    }

    @PostMapping("completeTask")
    @ApiOperation(value = "完成任务", notes = "")
    @ApiImplicitParams({@ApiImplicitParam(name = "taskId", value = "任务id", required = true, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "outcome", value = "连线名称", dataType = "String", required = true, paramType = "query")
            , @ApiImplicitParam(name = "comment", value = "批注", dataType = "String", required = true, paramType = "query")
            , @ApiImplicitParam(name = "userMassage", value = "办理人信息", dataType = "String", required = true, paramType = "query")
            , @ApiImplicitParam(name = "assignee", value = "下一步办理人", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "assigneeList", value = "办理人列表（子流程）", dataType = "String", paramType = "query")
    })
    public String completeTask(String taskId, String outcome, String comment, String userMassage, String assignee, String assigneeList) {
        WorkFlow workFlow = new WorkFlow();
        List<String> list = new ArrayList<>();
        Map<String, Object> variables = new HashMap();
        workFlow.setTaskId(taskId);
        workFlow.setOutcome(outcome);
        workFlow.setComment(comment);
        workFlow.setUserMassage(userMassage);
        if (StringUtils.isNotBlank(assigneeList)) {
            String[] assignees = assigneeList.split(",");
            for (String ass : assignees) {
                list.add(ass);
            }
            variables.put("assigneeList", list);
        }
        assignee = assignee.toString();
        variables.put("assignee", assignee);
        easyActService.completeTask(workFlow, variables);
        return "成功完成任务";
    }

    @ResponseBody
    @PostMapping("findEventByTaskId")
    @ApiOperation(value = "使用任务id查询业务详情", notes = "")
    @ApiImplicitParam(name = "taskId", value = "任务id", required = true, dataType = "String", paramType = "query")
    public Map<String, Object> findEventByTaskId(String taskId) {
        return easyActService.findEvent(taskId);
    }

//    @PostMapping("taskByUserId")
//    @ApiOperation(value = "使用UserId查询个人任务", notes = "")
//    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "query")
//    public List<TaskBean> findTaskListByUserId(String userId) {
//        List<TaskBean> list = easyActService.findTaskListByName(userId);
//        return list;
//    }

    @PostMapping("taskListByUserId")
    @ApiOperation(value = "查询正在执行的任务表，获取当前个人任务集合List<Task>", notes = "")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "query")
    public List<TaskBean> findTaskList(String userId) {//userId为task表中Assignee的值
        return easyActService.findTaskList(userId);
    }

    @PostMapping("findTaskListByUserId")
    @ApiOperation(value = "查询正在执行的任务表，获取当前个人任务的的id字符串", notes = "")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "query")
    public String findTaskListByUserId(String userId) {//userId为task表中Assignee的值
        return easyActService.findTaskListByUserId(userId);
    }

    @PostMapping("getTasksAndAssigneeNotnull")
    @ApiOperation(value = "获取当前个人任务的业务id列表", notes = "")
    public List<String> getTasksAndAssigneeNotnull() {
        return easyActService.getTasksAndAssigneeNotnull();
    }

    @PostMapping("getOrgs")
    @ApiOperation(value = "查询orgs", notes = "")
    @ApiImplicitParams({@ApiImplicitParam(name = "taskKey", value = "节点名称", required = true, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "id", value = "业务id", required = true, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "objectName", value = "实体类名称", required = true, dataType = "String", paramType = "query")
    })
    public List<String> getOrgs(String taskKey, String id, String objectName) {//userId为task表中Assignee的值
        return easyActService.getOrgs(taskKey, id, objectName);
    }
    @PostMapping("updateVar")
    @ApiOperation(value = "改变办理人assignee", notes = "")
    @ApiImplicitParams({@ApiImplicitParam(name = "assignee", value = "办理人", required = true, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "taskId", value = "任务id", required = true, dataType = "String", paramType = "query")
    })
    public int updateVar(String assignee,String taskId){//userId为task表中Assignee的值
        return easyActService.updateVar(assignee, taskId);
    }

    @PostMapping("findHisTaskList")
    @ApiOperation(value = "查询历史任务表，获取当前个人任务的集合List<HistoricTaskInstance>", notes = "")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "query")
    public List<String> findHisTaskList(String userId) {//userId为task表中Assignee的值
        return easyActService.findHisTaskList(userId);
    }

    @PostMapping("groupListByRoleId")
    @ApiOperation(value = "使用roleId查询组任务", notes = "")
    @ApiImplicitParam(name = "roleId", value = "角色id", required = true, dataType = "String", paramType = "query")
    public List<TaskBean> findGroupList(String roleId) {
        List<TaskBean> list = easyActService.findGroupList(roleId);
        return list;
    }

    @PostMapping("claim")
    @ApiOperation(value = "领取任务，组任务变为个人任务", notes = "")
    @ApiImplicitParams({@ApiImplicitParam(name = "taskId", value = "任务id", required = true, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "userId", value = "指定办理人", required = true, dataType = "String", paramType = "query")
    })
    public String claim(String taskId, String userId) {//任务ID,分配的办理人
        easyActService.claim(taskId, userId);
        return "success";
    }

    @PostMapping("rollbackGroup")
    @ApiOperation(value = "回退个人任务为组任务", notes = "")
    @ApiImplicitParam(name = "taskId", value = "任务id", required = true, dataType = "String", paramType = "query")
    public String rollbackGroup(String taskId) {//任务ID,分配的办理人
        easyActService.rollbackGroup(taskId);
        return "success";
    }

    @PostMapping("rollBackAct")
    @ApiOperation(value = "退回上一个节点", notes = "")
    @ApiImplicitParam(name = "taskId", value = "任务id", required = true, dataType = "String", paramType = "query")
    public String rollBackAct(String taskId) {
        return easyActService.rollBackAct(taskId);
    }

    @PostMapping("rollBackToAssignAct")
    @ApiOperation(value = "回退到指定节点", notes = "")
    @ApiImplicitParams({@ApiImplicitParam(name = "taskId", value = "任务id", required = true, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "destTaskkey", value = "指定节点key", required = true, dataType = "String", paramType = "query")
    })
    public String rollBackToAssignAct(String taskId, String destTaskkey) {
        return easyActService.rollBackToAssignAct(taskId, destTaskkey);
    }

    @ResponseBody
    @PostMapping("findCommentByObjecId")
    @ApiOperation(value = "使用业务ID，查询历史意见信息", notes = "")
    @ApiImplicitParams({@ApiImplicitParam(name = "className", value = "业务类名", required = true, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "id", value = "业务ID", required = true, dataType = "String", paramType = "query")
    })
    public List<Comment> findCommentByObjecId(String className, String id) {
        List<Comment> list = easyActService.findCommentByObjecId(className, id);//查询历史意见
        return list;
    }

    @ResponseBody
    @PostMapping("findOutComeListByTaskId")
    @ApiOperation(value = "使用任务ID，查询连线信息", notes = "")
    @ApiImplicitParam(name = "taskId", value = "任务ID", required = true, dataType = "String", paramType = "query")
    public List<String> findOutComeListByTaskId(String taskId) {
        List<String> list = easyActService.findOutComeListByTaskId(taskId);//查询历史意见
        return list;
    }

    @ResponseBody
    @PostMapping("findTask")
    @ApiOperation(value = "使用业务ID和办理人，查询任务id", notes = "")
    @ApiImplicitParams({@ApiImplicitParam(name = "objectId", value = "业务ID", required = true, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "objectName", value = "业务名称", required = true, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "assignee", value = "办理人", required = true, dataType = "String", paramType = "query")
    })
    public String findTask(String objectId, String objectName, String assignee) {
        String taskId = easyActService.findTask(objectId, objectName, assignee);//查询历史意见
        return taskId;
    }

    @ResponseBody
    @PostMapping("findAssigneeListByObjecId")
    @ApiOperation(value = "使用业务ID，查询当前节点办理人列表", notes = "")
    @ApiImplicitParams({@ApiImplicitParam(name = "objectName", value = "业务类名", required = true, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "id", value = "业务ID", required = true, dataType = "String", paramType = "query")
    })
    public List<String> findAssigneeListByObjecId(String objectName, String id) {
        List<String> assignees = easyActService.findAssigneeListByObjecId(objectName, id);//查询历史意见
        return assignees;
    }

    @ResponseBody
    @PostMapping("findTaskIdByObjecId")
    @ApiOperation(value = "使用业务ID，查询任务id", notes = "")
    @ApiImplicitParams({@ApiImplicitParam(name = "objectName", value = "业务类名", required = true, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "id", value = "业务ID", required = true, dataType = "String", paramType = "query")
    })
    public String findTaskIdByObjecId(String objectName, String id) {
        String taskId = easyActService.findTaskIdByObjecId(objectName, id);//查询历史意见
        return taskId;
    }

    @ResponseBody
    @PostMapping("findTaskIdOnlyOne")
    @ApiOperation(value = "使用业务ID，任务节点是否唯一", notes = "")
    @ApiImplicitParams({@ApiImplicitParam(name = "objectName", value = "业务类名", required = true, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "taskId", value = "任务ID", required = true, dataType = "String", paramType = "query")
    })
    public boolean findTaskIdOnlyOne(String objectName, String taskId) {
        boolean flag = easyActService.findTaskIdOnlyOne(objectName, taskId);
        return flag;
    }

    @ResponseBody
    @PostMapping("findTaskIdByObjecIdAndAssigneeIsNull")
    @ApiOperation(value = "使用业务ID，查询任务id,无办理人", notes = "")
    @ApiImplicitParams({@ApiImplicitParam(name = "objectName", value = "业务类名", required = true, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "id", value = "业务ID", required = true, dataType = "String", paramType = "query")
    })
    public String findTaskIdByObjecIdAndAssigneeIsNull(String objectName, String id,String roleids) {
        String taskId = easyActService.findTaskIdByObjecIdAndAssigneeIsNull(objectName, id,roleids);//查询历史意见
        return taskId;
    }

    @ResponseBody
    @PostMapping("findCoordingByTaskId")
    @ApiOperation(value = "查看坐标", notes = "查看当前活动，获取当期活动对应的坐标x,y,width,height")
    @ApiImplicitParam(name = "taskId", value = "任务id", required = true, dataType = "String", paramType = "query")
    public Map<String, Object> findCoordingByTask(String taskId) {
        return easyActService.findCoordingByTask(taskId);
    }

    @ResponseBody
    @PostMapping("getCount")
    @ApiOperation(value = "指定节点总数", notes = "")
    @ApiImplicitParams({@ApiImplicitParam(name = "taskKey", value = "节点key", required = true, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "assignees", value = "人员id拼串", dataType = "String", paramType = "query")
    })
    public int getCount(String taskKey, String assignees) {
        return easyActService.getCount(taskKey, assignees);
    }

}